import sys
import os
import json

config_file = os.path.join(os.path.dirname(__file__), "synchro.json")

if len(sys.argv) < 2:
    sys.exit("Few arguments\n")

work_file = sys.argv[1]
sample_suffix = sys.argv[2] if len(sys.argv) > 2 else ".sample"

if not os.path.exists(work_file):
    sys.exit("Work file not found\n")
if not os.path.exists(config_file):
    sys.exit("Config file not found\n")

wf_path_info = os.path.splitext(work_file)
sample_file = f"{wf_path_info[0]}{sample_suffix}{wf_path_info[1]}"

with open(config_file, "r") as file:
    replace_json = file.read()

try:
    replace_array = json.loads(replace_json)
except json.JSONDecodeError:
    sys.exit("Error json_decode\n")

with open(work_file, "r") as file:
    replaced_string = file.read()

for key, value in replace_array.items():
    replaced_string = replaced_string.replace(key, value)

with open(sample_file, "w") as file:
    file.write(replaced_string)
